package cn.highedu.coolsharkhub.controller;

import cn.highedu.coolsharkhub.service.UploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传控制器 处理文件上传相关请求
 */
@RestController
public class UploadController {
    Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    UploadService uploadService;
    /**
     * 文件上传 请求路径/upload 和前端页面的action一致
     * consumes = "multipart/form-data" 表示请求体中的数据类型是multipart/form-data, 和前端的enctype一致
     * @param imageFile 代表文件 参数名必须和前端页面中表单的name一致
     * @return
     */
    @PostMapping(value = "/upload", consumes = "multipart/form-data")
    public String upload(MultipartFile imageFile) {
        return uploadService.saveUploadFile(imageFile);
    }

    /**
     * 上传图片
     * @param imageFile
     * @return 文件存储的路径
     */
    @PostMapping(value = "/upload/images", consumes = "multipart/form-data")
    @ResponseStatus(HttpStatus.CREATED) // 201
    public String uploadImage(MultipartFile imageFile) {
        return uploadService.saveUploadFile(imageFile);
    }

    /**
     * 删除上传的文件
     * @param url 文件路径
     */
    @DeleteMapping("/upload/images")
    @ResponseStatus(HttpStatus.NO_CONTENT) // 204
    public void deleteImage(@RequestBody String url) {
        uploadService.deleteUploadFile(url);
    }
}
